# -*- coding:utf-8 -*-
import requests
from .dd_message import *
import time
import hmac
import hashlib
import base64
import urllib.parse


class DDRobot(object):
	
	def __init__(self, webhook_url=''):
		self.webhook_url = webhook_url
	
	def update_webhook_url(self, url):
		if url is not None:
			self.webhook_url = url
	
	def _post_message(self, data):
		headers = {"Content-Type": "application/json"}
		try:
			requests.post(self.webhook_url, data, headers=headers)
		except Exception as e:
			print(f'请求失败:{e}')
	
	def send_message(self, msgtype: MessageType, **kwargs):
		try:
			message = Message(msgtype)
			data = message.get_message(**kwargs).encode('utf-8')
			self._post_message(data)
		except Exception as e:
			print(e)


def get_webhook_url(token=None, secret=None):
	if secret is not None and token is not None:
		timestamp = str(round(time.time() * 1000))
		secret = 'SEC68af196b040a65d138e3209e44fd4b085b1d4db93b2aaf7bb058c8de5d0b29c1'
		secret_enc = secret.encode('utf-8')
		string_to_sign = '{}\n{}'.format(timestamp, secret)
		string_to_sign_enc = string_to_sign.encode('utf-8')
		hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
		sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
		print(timestamp)
		print(sign)
		post_url = f'https://oapi.dingtalk.com/robot/send?' \
		           f'access_token={token}' \
		           f'&timestamp={timestamp}&sign={sign}'
	elif token is not None:
		post_url = f'https://oapi.dingtalk.com/robot/send?' \
		           f'access_token={token}'
	else:
		raise ValueError('没有token,无法创建推送链接.')
	return post_url


if __name__ == '__main__':
	token = '36889f721b13044e3ca82346efd8a40d7c2356e8fcf2ffbd9d82fdad92e7da7b'
	secret = 'SEC68af196b040a65d138e3209e44fd4b085b1d4db93b2aaf7bb058c8de5d0b29c1'
	url = get_webhook_url(token, secret)
	robot = DDRobot(url)
	
	
	# Text消息发送
	data = {
		CONTENT: "你好,我是苍老师!",
		ISATALL: True,
		ATMOBILES: [],
		ATUSERIDS: []
	}
	robot.send_message(MessageType.text, **data)
	
	"""
	# Link消息发送
	data = {
		TITLE: '这是标题',
		TEXT: '这是消息内容',
		LINK_MESSAGE_URL: 'https://juejin.cn/post/6844903694509539336',
		LINK_PIC_URL: 'http://www.n63.com/photodir/n63img/?'
		              'N=X2hiJTI2ZGRXYSU1RVdnV2ElNUVXa1clNUVXJTVEa1dlZyU1QiUyNiUyQi5mJTI2'
		              'b29vJTI3YXBhWXIlMjdlWSU1RGpnYyUyNw%3D%3D&v=.jpg'
	}
	robot.send_message(MessageType.link, **data)
 
	# MarkDown消息发送
	data = {
		TITLE: '这是标题',
		TEXT: '这是Markdown内容',
		ISATALL: False,
		ATMOBILES: [],
		ATUSERIDS: []
	}
	robot.send_message(MessageType.markdown, **data)
	
	# ActionCard整体消息发送
	data = {
		TITLE: '这是标题',
		TEXT: '这是 ActionCard 内容',
		AC_BTN_ORIENTATION: '0',
		AC_SINGLE_URL: 'https://www.baidu.com',
		AC_SINGLE_TITLE: 'ActionCard 标题',
	}
	robot.send_message(MessageType.actionCard, **data)
	
	# ActionCard 独立消息发送(主要是传入的消息格式与上不一样)
	data = {
		AC_BTNS: [
			{
				AC_TITLE: '内容不错',
				AC_ACTION_URL: 'https://www.dingtalk.com'
			},
			{
				AC_TITLE: '不敢兴起',
				AC_ACTION_URL: 'https://www.baidu.com'
			},
		]
	}
	robot.send_message(MessageType.actionCard, **data)
	
	# FeedCard 独立消息发送)
	data = {
		FC_LINKS: [
			{
				FC_LINK_TITLE: '内容不错',
				FC_MESSAGE_URL: 'https://www.dingtalk.com',
				FC_PIC_URL: 'https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png'
			},
			{
				FC_LINK_TITLE: '标题不错',
				FC_MESSAGE_URL: 'https://www.dingtalk.com',
				FC_PIC_URL: 'https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png'
			},
			{
				FC_LINK_TITLE: '内容真不错',
				FC_MESSAGE_URL: 'https://www.dingtalk.com',
				FC_PIC_URL: 'https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png'
			},
			{
				FC_LINK_TITLE: '标题真不错',
				FC_MESSAGE_URL: 'https://www.dingtalk.com',
				FC_PIC_URL: 'https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png'
			},
		],
	}
	robot.send_message(MessageType.feedCard, **data)
	"""
